import CryptoJS  from 'crypto-js';
import { CryptoEnum } from '@/enums/Crypto';

function setCookie(key:string, item:any, days:number) {
    const day = days ? days : 1000;
    // 设置过期时间
    const time = new Date(
        new Date().getTime() + day * 24 * 60 * 60 * 1000
    ).toUTCString();

    const ciphertext = CryptoJS.AES.encrypt(JSON.stringify(item), CryptoEnum.SECRETKEY).toString();
    document.cookie = key + "=" + ciphertext + "; expires=" + time;
} 

/** 
 * @description 获取cookie
 * @param {String} name 需要获取cookie的key
 */
function getCookie(name:string) {
    const ciphertext:any = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
    if(ciphertext){
        const bytes  = CryptoJS.AES.decrypt(ciphertext[2], CryptoEnum.SECRETKEY);
        const decryptedData = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
        if (decryptedData != null) 
            return decryptedData;
        else 
            return null;
    }else{
        return null;
    }
}

/** 
 * @description 删除cookie
 * @param {String} name 需要删除cookie的key
 */
function clearCookie(name:string) {
    setCookie(name, '', -1)
}

export default {
    setCookie,
    getCookie,
    clearCookie
}